using System;
using System.Collections.Generic;
using System.Text;
using System.Net;
using System.IO;
using System.Xml;
using System.Web;
using System.Data;

namespace MSNClient
{
    class MsnClient_SOAP
    {
        /// <summary>
        /// Password 3.0
        /// </summary>
        ///        
        String TicketUrl = "https://loginnet.passport.com/RST.srf";
        MsnServicesTemplate msnService;
        WebClient webClient;
        FindMembershipResult membershipData;
        ABFindAllResult contactListData;
        
        public MsnClient_SOAP()
        {
            msnService = new MsnServicesTemplate();
        }
        public String GetAllowList(TicketData iTicket)
        {
            String fs = GetMembershipData(iTicket);
            String allowList="<ml l=\"1\"></ml>";
            String endTag = "</ml>";
            String newDataPatter = "<d n=\"{0}\"><c n=\"{1}\" l=\"3\" t=\"1\" /></d>";
            String domainPatter = "<d n=\"{0}\">";
            String memberPatter = "<c n=\"{0}\" l=\"3\" t=\"1\" />";

            if (membershipData == null)
            {
                return allowList;
            }
            for (int i = 0 ; i < membershipData.Services.Length ; i++)
            {
                for(int j=0 ; j<membershipData.Services[i].Memberships.Length ; j++)
                {
                    if (membershipData.Services[i].Memberships[j].MemberRole == MemberRoles.Allow)
                    {
                        Member[] members = membershipData.Services[i].Memberships[j].Members;
                        for (int k = 0; k < members.Length; k++)
                        {
                            /*
                            if (members[i].Type == MemberType.Email)
                            {
                                Console.WriteLine(members[]);
                            }
                             * */
                            if (!members[k].Deleted && members[k].Type == MemberType.Passport)
                            {
                                PassportMember passMember = (PassportMember)members[k];
                                //First part of accountName data before '@'
                                String userName = passMember.PassportName.Split('@')[0];
                                //Domain nama 'domain.com'
                                String domain = passMember.PassportName.Split('@')[1];
                                //Checking if this domain already added
                                if(allowList.Contains(passMember.PassportName.Split('@')[1]))
                                {
                                    //Search string contains domain tag pattern "<d n="domain.com">";
                                    String searchString = String.Format(domainPatter,domain);
                                    String newMemberData = String.Format(memberPatter, userName);
                                    allowList = allowList.Insert(allowList.IndexOf(searchString)+searchString.Length, newMemberData);
                                }
                                    //Then adding this fomain to aalowList with new memberNae
                                else
                                {
                                    /*
                                     * d = domain, c = contactName :)
                                     */
                                    String newData = String.Format(newDataPatter, domain, userName);
                                    allowList = allowList.Insert(allowList.IndexOf(endTag), newData);
                                }
                            }
                        }
                    }
                }
            }
            return allowList;

        }
        public ContactInfo[] GetContactList(TicketData iTicket)
        {
            ABHeadersInitialize(iTicket);
            contactListData = msnService.ABFindAll(new Guid(), "Full", false, new DateTime());
            ContactInfo[] result = new ContactInfo[contactListData.contacts.Length];
            for (int i = 0; i < result.Length; i++)
            {
                result[i] = contactListData.contacts[i].contactInfo;
            }
            return result;
        }
        private void ABHeadersInitialize(TicketData iTicket)
        {
            //First header
            if (msnService.ABApplicationHeaderValue == null)
            {
                msnService.ABApplicationHeaderValue = new ABApplicationHeader();
            }
            msnService.ABApplicationHeaderValue.ApplicationId = new Guid("CFE80F9D-180F-4399-82AB-413F33A1FA11");
            msnService.ABApplicationHeaderValue.IsMigration = false;
            msnService.ABApplicationHeaderValue.PartnerScenario = "Initial";

            //Second header
            if (msnService.ABHeaderValue == null)
            {
                msnService.ABHeaderValue = new ABHeader();
            }
            msnService.ABHeaderValue.ManagedGroupRequest = false;
            msnService.CookieContainer = new System.Net.CookieContainer();
            msnService.CookieContainer.SetCookies(new Uri("http://contacts.msn.com"), "MSPAuth=" + iTicket.MSPAuth+";MSPProf="+iTicket.MSPProf);

        }
        public String GetMembershipData(TicketData iTicket)
        {
            ABHeadersInitialize(iTicket);

            ServiceTypes sm = new ServiceTypes();
            sm.Types = new ServiceType[] { ServiceType.Messenger};
            //sm.Types = new ServiceType[] { ServiceType.Messenger, ServiceType.Invitation, ServiceType.SocialNetwork, ServiceType.Space, ServiceType.Profile };

            Console.WriteLine("GetContactList\n");
            try
            {
                membershipData = msnService.FindMembership(sm, "Full", false, new DateTime());
            }
            catch (WebException we)
            {
                Console.WriteLine("WebException Getting ContactList:");
                Console.WriteLine(we.StackTrace);
                Console.WriteLine(we.Message);
            }
            catch (Exception e)
            {
                Console.WriteLine("Error Getting ContactList:");
                Console.WriteLine(e.StackTrace);
            }

            return "";
        }
        public String GetTicket(String aLogin, String aPassword, String aTwnData)
        {
            webClient = new WebClient();
            webClient.Headers.Add(HttpRequestHeader.Accept, "text/*");
            webClient.Headers.Add(HttpRequestHeader.UserAgent, "Mozilla/4.0 (compatible; MSIE 6.0; Windows NT 5.1)");
            byte[] buffer = webClient.UploadData(TicketUrl, Encoding.UTF8.GetBytes(GetTicketRequestString(aLogin, aPassword, aTwnData)));
            String response = Encoding.UTF8.GetString(buffer);
            if (MsnClient.WriteDebugDataToFile)
            {
                MsnClient.WriteToFile("C:\\Documents and Settings\\" + Environment.UserName + "\\Desktop\\Msn_Client_Debug_Data\\response.xml", response);
            }
            XmlDocument document = new XmlDocument();
            document.LoadXml(response);
            XmlNodeList xmlNodeList = document.GetElementsByTagName("wsse:BinarySecurityToken");
            if (xmlNodeList.Count > 0)
            {
                return xmlNodeList[0].InnerText.Replace("t=","");
            }
            return "";


        }
        String GetTicketRequestString(String aLogin, String aPassword, String aTwnData)
        {
            aTwnData = aTwnData.Replace(",", "&amp;");
            aTwnData = HttpUtility.UrlDecode(aTwnData);

            String request = "<?xml version=\"1.0\" encoding=\"UTF-8\"?>"
                + "<Envelope xmlns=\"http://schemas.xmlsoap.org/soap/envelope/\" xmlns:wsse=\"http://schemas.xmlsoap.org/ws/2003/06/secext\" "
                + "xmlns:saml=\"urn:oasis:names:tc:SAML:1.0:assertion\" xmlns:wsp=\"http://schemas.xmlsoap.org/ws/2002/12/policy\" "
                + "xmlns:wsu=\"http://docs.oasis-open.org/wss/2004/01/oasis-200401-wss-wssecurity-utility-1.0.xsd\" "
                + "xmlns:wsa=\"http://schemas.xmlsoap.org/ws/2004/03/addressing\" "
                + "xmlns:wssc=\"http://schemas.xmlsoap.org/ws/2004/04/sc\" "
                + "xmlns:wst=\"http://schemas.xmlsoap.org/ws/2004/04/trust\">"
                + "<Header>"
                + "<ps:AuthInfo xmlns:ps=\"http://schemas.microsoft.com/Passport/SoapServices/PPCRL\" Id=\"PPAuthInfo\">"
                + "<ps:HostingApp>{7108E71A-9926-4FCB-BCC9-9A9D3F32E423}</ps:HostingApp>"
                + "<ps:BinaryVersion>4</ps:BinaryVersion>"
                + "<ps:UIVersion>1</ps:UIVersion>"
                + "<ps:Cookies></ps:Cookies>"
                + "<ps:RequestParams>AQAAAAIAAABsYwQAAAAzMDg0</ps:RequestParams>"
                + "</ps:AuthInfo>"
                + "<wsse:Security>"
                + "<wsse:UsernameToken Id=\"user\">"
                + "<wsse:Username>" + aLogin + "</wsse:Username>"
                + "<wsse:Password>" + aPassword + "</wsse:Password>"
                + "</wsse:UsernameToken>"
                + "</wsse:Security>"
                + "</Header>"
                + "<Body>"
                + "<ps:RequestMultipleSecurityTokens xmlns:ps=\"http://schemas.microsoft.com/Passport/SoapServices/PPCRL\" Id=\"RSTS\">"
                + "<wst:RequestSecurityToken Id=\"RST0\">"
                + "<wst:RequestType>http://schemas.xmlsoap.org/ws/2004/04/security/trust/Issue</wst:RequestType>"
                + "<wsp:AppliesTo>"
                + "<wsa:EndpointReference>"
                + "<wsa:Address>http://Passport.NET/tb</wsa:Address>"
                + "</wsa:EndpointReference>"
                + "</wsp:AppliesTo>"
                + "</wst:RequestSecurityToken>"
                + "<wst:RequestSecurityToken Id=\"RST1\">"
                + "<wst:RequestType>http://schemas.xmlsoap.org/ws/2004/04/security/trust/Issue</wst:RequestType>"
                + "<wsp:AppliesTo>"
                + "<wsa:EndpointReference>"
                + "<wsa:Address>messenger.msn.com</wsa:Address>"
                + "</wsa:EndpointReference>"
                + "</wsp:AppliesTo>"
                + "<wsse:PolicyReference URI=\"?"+aTwnData+"\"></wsse:PolicyReference>"
                + "</wst:RequestSecurityToken>"
                + "</ps:RequestMultipleSecurityTokens>"
                + "</Body>"
                + "</Envelope>";
            return request;
        }


    }
}
